package com.cango.student.mapsort;

import java.util.*;
import java.util.Map.Entry;

/**
 * map排序
 */
public class mapSort {

    private static void nomalSortByKeyDesc() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("b", "b");
        map.put("a", "c");
        map.put("c", "a");

        // 通过ArrayList构造函数把map.entrySet()转换成list
        List<Map.Entry<String, String>> list = new ArrayList<>(map.entrySet());

        // 通过比较器实现比较排序
        Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> mapping1, Map.Entry<String, String> mapping2) {
                return mapping1.getKey().compareTo(mapping2.getKey());
            }
        });

        for (Map.Entry<String, String> mapping : list) {
            System.out.println(mapping.getKey() + " ：" + mapping.getValue());
        }
    }

    private static void sortByKeyDesc() {
        TreeMap<String, String> tm = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o2.compareTo(o1);
            }
        });
        tm.put("a", "ddd");
        tm.put("b", "ccc");
        tm.put("c", "bbb");
        tm.put("d", "aaa");
        for (String key : tm.keySet()) {
            System.out.println("key :" + key + ",value：" + tm.get(key));
        }
    }

    private static void sortByValueDesc() {
        Map<String, String> tm = new TreeMap<String, String>();
        tm.put("a", "ddd");
        tm.put("b", "ccc");
        tm.put("c", "bbb");
        tm.put("d", "aaa");
        //这里将map.entrySet()转换成list
        List<Map.Entry<String, String>> list = new ArrayList<>(tm.entrySet());
        //然后通过比较器来实现排序
        Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
            //降序排序
            @Override
            public int compare(Entry<String, String> o1, Entry<String, String> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        for (Map.Entry<String, String> mapping : list) {
            System.out.println(mapping.getKey() + ":" + mapping.getValue());
        }
    }

    // 当length总是 2 的n次方时，h& (length-1)运算等价于对length取模
    static int indexFor(int h, int length) {
        return h & (length-1);
    }

    public static void main(String[] args) {
        System.out.println(indexFor(10,8));

//        nomalSortByKeyDesc();
//        sortByKeyDesc();
//        sortByValueDesc();
    }
}
